package jbstoremgmt.web;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import jbstoremgmt.dao.BPDAO;
import jbstoremgmt.domain.Address;
import jbstoremgmt.domain.BPMaster;
import jbstoremgmt.service.BPDetailsBean;
import jbstoremgmt.service.BPListBean;
import jbstoremgmt.util.UtilHelper;

import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.multiaction.MultiActionController;

public class BPGenericController extends MultiActionController {

	private BPDAO bpDAO;

	public void setBpDAO(BPDAO bpDAO) {
		this.bpDAO = bpDAO;
	}

	public ModelAndView getBpList(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		// Populate List of All Business Partners & show it in a list.

		String action_type = request.getParameter("action_type") == null ? "action_default"
				: request.getParameter("action_type");
		String item_id = request.getParameter("item_id");
		int noOfRows = 0;

		if (action_type.equals("action_delete")) {
			noOfRows = bpDAO.deleteBP(Integer.parseInt(item_id));
		}

		if (action_type.equals("action_modify")) {
			BPMaster bpMasterBean = new BPMaster();
			Address address = new Address();

			address.setAddress_Id(Integer.parseInt(request.getParameter(item_id
					+ "_address_Id")));
			address.setAddr1(request.getParameter(item_id + "_addr1"));
			address.setAddr2(request.getParameter(item_id + "_addr2"));
			address.setCity(request.getParameter(item_id + "_city"));
			address.setState(request.getParameter(item_id + "_state"));
			address.setCountry(request.getParameter(item_id + "_country"));

			bpMasterBean.setBp_id(Integer.parseInt(item_id));
			bpMasterBean.setBp_fname(request
					.getParameter(item_id + "_bp_fname"));
			bpMasterBean.setBp_mname(request
					.getParameter(item_id + "_bp_mname"));
			bpMasterBean.setBp_lname(request
					.getParameter(item_id + "_bp_lname"));
			bpMasterBean.setBp_address(address);
			
			bpDAO.modifyBP(bpMasterBean);
		}

		List<BPDetailsBean> bpDetailsList = new ArrayList<BPDetailsBean>();
		List<BPMaster> bpListBean = bpDAO.getBPAll();

		for (BPMaster element : bpListBean) {
			BPDetailsBean bpDetailsBean = new BPDetailsBean();
			UtilHelper.copyProperties(bpDetailsBean, element);
			bpDetailsList.add(bpDetailsBean);
		}
		Collections.sort(bpDetailsList);
		return new ModelAndView("bplist", "bpDetailsList", bpDetailsList);
	}
}
